// tslint:disable
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core';
import { Base64ToGallery } from '@ionic-native/base64-to-gallery/ngx';
import QRCode from 'qrcode';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { ExportAsService, ExportAsConfig } from 'ngx-export-as';
import { ShareService } from 'src/app/shared/service/share.service';
import { EventService } from 'src/app/shared/service/event.service';
import { LoadingController } from '@ionic/angular';
import { HttpService } from 'src/app/shared/service/http.service';
import { UploadImageService } from 'src/app/shared/service/uploadImageService';
import { time } from 'console';
import { resolve } from 'dns';

@Component({
  selector: 'app-qrcode',
  templateUrl: './qrcode.component.html',
  styleUrls: ['./qrcode.component.scss'],
})
export class QrcodeComponent implements OnInit {
  @Input() tagData: any;
  qrCodeUrl: any;

  topImagUrl: any;
  centerImagUrl: any;
  bottomImagUrl: any;
// 名片img
  qrcodeUrl: any;
  logoUrl: any;
  phoneIconUrl: any;
  bgImg: any;

  exportAsConfig: ExportAsConfig = {
    type: 'png', // the type you want to download
    elementId: 'html2canvas' // the id of html/table element
  };
  appTypeCustom: any;
  uuid = 'qruuid';
  defaultCenterLogo = '';
  avatarIcon = '';
  loaderToShow: any;
  imgCount = 0;
  imgSuccessCount = 0;
  constructor(
    private exportAsService: ExportAsService,
    public gloadService: AppGlobalService,
    private shareService: ShareService,
    private eventService: EventService,
    private ref: ChangeDetectorRef,
    private http: HttpService,
    private loadingController: LoadingController,
    private uploadService: UploadImageService,
    private base64ToGallery: Base64ToGallery
  ) {

    if (this.eventService.eventEmit.listenerCount("qrCode") > 0) {
      this.eventService.eventEmit.removeListener("qrCode");
    }
    this.eventService.eventEmit.on('qrCode', data => {
      if (localStorage.getItem('qrCodeRequestCode')) {
        localStorage.removeItem('qrCodeRequestCode');
        this.savePhoto(data);
      }


    });

  }

  ngOnInit() {
    window['appGlobalService'].loadSharePicCallBack =(domId)=>{};
    let that =this;
    this.imgCount = 0;
    this.imgSuccessCount = 0;
    this.uuid += new Date().getTime();
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    let qrCodeUrl = '';

    if (this.tagData.data.qrCodeUrl !== undefined) {
      qrCodeUrl = this.tagData.data.qrCodeUrl;
    }
    if (this.tagData.data.info && this.tagData.data.info.qrCodeUrl !== undefined) {
      qrCodeUrl = this.tagData.data.info.qrCodeUrl;
    }

    if (qrCodeUrl) {
      QRCode.toDataURL(qrCodeUrl)
        .then(url => {
          // console.log(url);
          console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	toDataURL.then   ', '  	 generate url success.  ');
          this.qrCodeUrl = url;
        })
        .catch(err => {
          console.log('QRCode.toDataURL' + err);
        });
    }

    if (this.tagData.data.info && this.tagData.data.info.centerLogo !== undefined) {
      this.getBase64Image(this.tagData.data.info.centerLogo, (dataUrl) => {
        this.imgCount += 1;// 名片用到
        this.defaultCenterLogo = dataUrl;
      })
    }

    if (this.tagData.data.info && this.tagData.data.info.avatarPic !== undefined) {
      this.getBase64Image(this.tagData.data.info.avatarPic, (dataUrl) => {
        // console.log('dataUrl2=', dataUrl);
        this.avatarIcon = dataUrl;
      })
    }
    // if (this.tagData.data.info && this.tagData.data.info.qrcodeUrl) {
    //   this.imgCount += 1;
    //   this.getBase64Image(this.tagData.data.info.qrcodeUrl, (dataUrl) => {
        
    //     this.qrcodeUrl = dataUrl;
    //   })

    // }

    if (this.tagData.data.info && this.tagData.data.info.logoUrl ) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.logoUrl, (dataUrl) => {
        
        this.logoUrl = dataUrl;
      })

    }

    if (this.tagData.data.info && this.tagData.data.info.phoneIconUrl ) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.phoneIconUrl, (dataUrl) => {
        
        this.phoneIconUrl = dataUrl;
      })

    }
    if (this.tagData.data.info && this.tagData.data.info.bgImg ) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.bgImg, (dataUrl) => {
        
        this.bgImg = dataUrl;
      })

    }
    
// 同步名片编辑预览
    if (this.eventService.eventEmit.listenerCount("synchLogo") > 0) {
      this.eventService.eventEmit.removeListener("synchLogo");
    }
    this.eventService.eventEmit.on('synchLogo', data => {
      this.tagData.data.info.logoUrl = data;
      this.getBase64Image(this.tagData.data.info.logoUrl, (dataUrl) => {
        this.logoUrl = dataUrl;
      })
    });

    if (this.eventService.eventEmit.listenerCount("synchName") > 0) {
      this.eventService.eventEmit.removeListener("synchName");
    }
    this.eventService.eventEmit.on('synchName', data => {
      this.tagData.data.info.nickName = data;
    });

    if (this.eventService.eventEmit.listenerCount("synchJob") > 0) {
      this.eventService.eventEmit.removeListener("synchJob");
    }
    this.eventService.eventEmit.on('synchJob', data => {
      this.tagData.data.info.job = data;

    });
    if (this.eventService.eventEmit.listenerCount("synchPhone") > 0) {
      this.eventService.eventEmit.removeListener("synchPhone");
    }
    this.eventService.eventEmit.on('synchPhone', data => {
      this.tagData.data.info.phone = data;

    });
    if (this.eventService.eventEmit.listenerCount("synchCpyName") > 0) {
      this.eventService.eventEmit.removeListener("synchCpyName");
    }
    this.eventService.eventEmit.on('synchCpyName', data => {
      this.tagData.data.info.cpyName = data;

    });


    if (this.tagData.data.info && this.tagData.data.info.topImagUrl !== undefined) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.topImagUrl, (dataUrl) => {
        
        this.topImagUrl = dataUrl;
      })

    }

    if (this.tagData.data.info && this.tagData.data.info.centerImagUrl !== undefined) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.centerImagUrl, (dataUrl) => {
        
        this.centerImagUrl = dataUrl;
      })
    }

    if (this.tagData.data.info && this.tagData.data.info.bottomImagUrl !== undefined) {
      this.imgCount += 1;
      this.getBase64Image(this.tagData.data.info.bottomImagUrl, (dataUrl) => {
        
        this.bottomImagUrl = dataUrl;
      })
    }

    if (this.tagData.data.info.uploadImgMode
      && this.tagData.data.info.isUpload
      && (this.tagData.data.info.isUpload === '1')) {
      if (this.tagData.data.info && (this.tagData.data.info.topImagUrl !== undefined
        || this.tagData.data.info.centerImagUrl !== undefined
        || this.tagData.data.info.bottomImagUrl !== undefined
        // 名片的
        || this.tagData.data.info.qrodeUrl !== undefined
        || this.tagData.data.info.logoUrl !== undefined
        || this.tagData.data.info.phonrIconUrl !== undefined
        || this.tagData.data.info.bgImg !== undefined
      )) {
        this.gloadService.loadSharePicCallBack = (domId) => {

          const targetImagElement = document.getElementById(domId) as HTMLImageElement;
          if (targetImagElement && targetImagElement.complete) {
            that.imgSuccessCount += 1;
            console.log('' + domId, 'render image complete...');
            targetImagElement.onload = null; // 

            that.gloadService.isUploadImgComplete = false; // qrcode组件才会用到这个字段
            console.log('imgCount=',that.imgCount);
            console.log('imgSuccessCount=',that.imgSuccessCount);
            if (that.imgSuccessCount > 0 && (that.imgCount === that.imgSuccessCount)) {
              // 2024.05.30 预留50ms用于图片缓冲渲染
              that.uploadImage();
            }
          }

        }
      };
    }
  }







  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }


  updateHtml2Canvans() {
    const width = this.tagData.data.info.html2canvasWidth ? this.tagData.data.info.html2canvasWidth : 'calc(100vw - 8.5rem)';
    const height = this.tagData.data.info.html2canvasHeight ? this.tagData.data.info.html2canvasHeight : 'calc(82vw - 6.97rem)'; // 使用等比例计算
    const paddingLeft = this.tagData.data.info.html2canvasPaddingLeft ? this.tagData.data.info.html2canvasPaddingLeft : '0rem';
    if (document.getElementById('html2canvas')) {
      document.getElementById('html2canvas').style.width = width;
      document.getElementById('html2canvas').style.height = height;
      document.getElementById('html2canvas').style.paddingLeft = paddingLeft;
    }
  }



  uploadImage() {
    this.updateHtml2Canvans();
    const that = this;
    setTimeout(() => {
      const element = document.getElementById('html2canvas');
      const targetElement = document.getElementById('qr-bg' + this.uuid).cloneNode(true);
      element.appendChild(targetElement);
      this.exportAsService.get(this.exportAsConfig).subscribe(content => {
        // console.log('content=', content);

        let reader = new FileReader();
        const selectImg = this.uploadService.convertBase64ToBlob(content);
        // reader.readAsDataURL(selectImg);
        // reader.onload = (e) => {
        const uploadData = new FormData();
        uploadData.append('file', selectImg, new Date().getTime + '.jpg');
        let path = 'file/simpleUpload?waterMark=蜂喔';
        that.http.img_post(path, uploadData, res => {
          that.hideLoader();
          that.gloadService.isUploadImgComplete = true; // 更新状态
          let url = JSON.stringify(res.url).toString();
          console.log('message----->' + url);
          url = url.replace('"', '').replace('"', '');

          that.gloadService.updateImageSubmit.submit.content.share_pic = url;

          const params = {
            content: that.gloadService.updateImageSubmit.submit.content,
            id: that.gloadService.updateImageSubmit.submit.id,
            sessionId: localStorage.getItem('sessionId')
          };
          // 请求获取新数据
          that.http.post('application/submit', params, respo => {
            // 请求数据成功
            if (respo.success) {
              // this.appGlobalService.reloadCurrentPage();
              // this.gloadService.showToast(respo.message, 2000, 'middle');
              console.log(respo.message);
            } else {
              // 请求数据失败
              this.gloadService.showToast(respo.message, 2000, 'middle');
            }
          },
            err => {
              // 请求数据失败
              this.gloadService.showToast(err.message, 2000, 'middle');
            });

        }, err => {
          that.hideLoader();
        });
        // }

        element.removeChild(targetElement);
      });
    }, 200);
  }

  showLoader() {
    this.loaderToShow = this.loadingController.create({
      message: '上传文件中...'
    }).then((res) => {
      res.present();
      res.onDidDismiss().then((dis) => {
        this.ref.detectChanges(); // trigger change detection cycle
      });
    });
    // this.hideLoader();
  }

  hideLoader() {
    setTimeout(() => {
      if (this.loadingController) {
        this.loadingController.dismiss();
      }
    }, 1000);
  }




  blobToBase64(blob, callback) { //blob转base64
    let reader = new FileReader();
    reader.onload = (e) => { callback(e); }
    reader.readAsDataURL(blob);
  }

  // 2024.05.06用于便利超市上传图片到商品表
  savePhoto2() {
    this.updateHtml2Canvans();
    setTimeout(() => {
      this.savePhoto();
    }, 50);
  }

  savePhoto(data?) {
    const that = this;
    const element = document.getElementById('html2canvas');
    const targetElement = document.getElementById('qr-bg' + this.uuid).cloneNode(true);
    element.appendChild(targetElement);
    this.exportAsService.get(this.exportAsConfig).subscribe(content => {

      if (data && typeof (data) === 'object') {
        that.download(content, data.name === 'tikTok' ? true : false, data.title, data.content, data.imageUrl, data.name);
      } else {
        that.download(content);
      }

      element.removeChild(targetElement);
    });
  }
  download(dataUrl, isFromDouyin?, title?, description?, webpageUrl?, type?) {
    if (localStorage.getItem('client') === 'BROWSER') {
      const myBlob = this.dataURLtoBlob(dataUrl);
      const myUrl = URL.createObjectURL(myBlob);
      this.downloadFile(myUrl, 'deatil');
      this.setBtnEnable(type + this.uuid);
    } else {
      // if (type) {
      //   const myBlob = this.dataURLtoBlob(dataUrl);
      //   this.uploadForUrl(myBlob, (url) => {
      //     if (type === 'wechat') {
      //       this.shareService.shareWeiXinImage(title, description, url, webpageUrl);
      //     } else if (type === 'qq') {
      //       this.shareService.shareQQImage(title, description, url, webpageUrl);
      //     }
      //   });
      // } else {
      this.base64ToGallery.base64ToGallery(dataUrl, { prefix: isFromDouyin ? 'isFromDouyin' : '_img', mediaScanner: true }).then(
        (res) => {
          this.setBtnEnable(type + this.uuid);
          console.log('Saved image to gallery ', res);
          if (isFromDouyin) {
            const filePath = "file://" + res;
            const fileArray = [filePath];
            this.shareService.shareDouyin(title, description, fileArray, webpageUrl);
          } else if (type && type === 'wechat') {
            if (localStorage.getItem('platform') === 'android') {
              this.shareService.shareWeiXinImage(title, description, dataUrl, dataUrl);
            } else {
              this.shareService.shareWeiXinImage(title, description, res, res);
            }
          } else if (type && type === 'qq') {
            if (localStorage.getItem('platform') === 'android') {
              this.shareService.shareQQImage(title, description, dataUrl, dataUrl);
            } else {
              this.shareService.shareQQImage(title, description, res, res);
            }
          } else {
            this.gloadService.showToast('保存成功!', 1500, 'top');
          }
        },
        err => console.log('Error saving image to gallery ', err)
      );
      // }
    }
  }
  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  downloadFile(url, name) {
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  }
  demoData() {
    this.tagData = {
      type: "tag",
      style: "qrcode.tag",
      name: "****",
      layout: "body",
      data: {
        tips: "支付成功后请下拉刷新签约页面",
        ppwLogo: "ppw_logo@3x.png",
        serviceContent: "秋晓朦邀您开通铺铺旺转店快服务付款3000元",
        qrCodeUrl: "https://pay.pupuwang.com/pay",
        qrTips: "打开支付宝或者微信扫码支付",
        resultTips: "此客户未注册，付款成功后自动注册， 账号将短信发送给客户",
        saveBtn: "保存图片"
      }

    };
  }

  shareWechat(isDouyin, title, content, imgUrl, webpageUrl) {
    this.savePic(isDouyin, title, content, webpageUrl, 'wechat');
  }
  shareQQ(isDouyin, title, content, imgUrl, webpageUrl) {
    this.savePic(isDouyin, title, content, webpageUrl, 'qq');
  }

  savePic(isFromDouyin?, title?, description?, webpageUrl?, type?) {
    const btnId = type + this.uuid;
    this.setBtnDisabled(btnId);
    const that = this;
    const element = document.getElementById('html2canvas');

    const targetElement = document.getElementById('qr-bg' + this.uuid).cloneNode(true);
    // crossOrigin="anonymous"
    element.appendChild(targetElement);
    this.exportAsService.get(this.exportAsConfig).subscribe(content => {
      that.download(content, isFromDouyin, title, description, webpageUrl, type);
      element.removeChild(targetElement);
    });
  }
  copyUrl(isFromDouyin?, title?, description?, webpageUrl?, type?) {
    this.shareService.copyUrl(webpageUrl)
    // const btnId = type + this.uuid;
    // this.setBtnDisabled(btnId);
    // const that = this;
    // const element = document.getElementById('html2canvas');

    // const targetElement = document.getElementById('qr-bg').cloneNode(true);
    // // crossOrigin="anonymous"
    // element.appendChild(targetElement);
    // this.exportAsService.get(this.exportAsConfig).subscribe(content => {
    //   that.download(content, isFromDouyin, title, description, webpageUrl, type);
    //   element.removeChild(targetElement);
    // });
  }

  setBtnDisabled(id) {
    if (document.getElementById(id)) {
      try {
        document.getElementById(id).setAttribute("disabled", "true");
      } catch (error) {
      }
    }
  }

  setBtnEnable(id) {
    if (document.getElementById(id)) {
      try {
        document.getElementById(id).removeAttribute("disabled");
      } catch (error) {
      }
    }
  }
  public getBase64Image(imgUrl: string, callBackFunction: (dataUrl: string) => void): Promise<string> {
    return new Promise<string>((resolve, reject) => {
      if (imgUrl){
        const img = new Image();
        img.crossOrigin = 'anonymous'; // 注意这里设置crossOrigin属性而不是使用setAttribute  
  
        img.onload = () => {
          const canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL("image/png");
          callBackFunction(dataURL);
          resolve(dataURL.replace(/^data:image\/(png|jpeg);base64,/, "")); // 注意这里也可能是jpeg而不是jpg  
        };
  
        img.onerror = (error) => {
          // 在这里处理图片加载错误  
          reject(new Error(`Failed to load image: ${imgUrl}`));
          console.error('Image load error----->', error);
        };
  
        img.src = imgUrl; // 最后设置src属性以触发加载  
      } else {
        resolve("");
      }
      
    });
  }


  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    this.eventService.removeAllListeners('qrCode');
    window['appGlobalService']['loadSharePicCallBack'] = null;
  }

  getInterger(value) {
    return parseInt(value);
  }


}
